package com.iweb.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JdbcUtil {
    static Connection conn=null;//数据库连接
    static PreparedStatement stat=null;//操作sql语句的对象
    static ResultSet rest=null;//查询语句执行的结果集
    static ResultSetMetaData rsmd=null;//它用来获取ResultSet中列相关
    //获取资源
    private static Connection getConn(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取数据库连接
            conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/second_hand_trading?characterEncoding=utf-8","root","123456");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }
    public static void closeSrc(){
        try {
            //关闭资源
            if(rest!=null)
                rest.close();
            if(stat!=null)
                stat.close();
            if(conn!=null)
                conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //增删改方法
    public static <E> int editBySql(String sql,E... e){
        conn=getConn();
        int result=0;
        //获取statement对象
        try {
            stat=conn.prepareStatement(sql);//获取statement对象
            for(int i=0;i<e.length;i++){
                stat.setObject(i+1,e[i]);
            }
            result=stat.executeUpdate();
        } catch (SQLException e1) {
            throw new RuntimeException(e1);
        }finally {
            closeSrc();
        }
        return result;
    }
    //查询方法
    public static <E> List<Map<String,Object>> selectBySql(String sql,E... e){
        List<Map<String,Object>> list=new ArrayList<>();
        //加载Oracle的驱动类
        try {
            conn=getConn();
            //获取statement对象
            stat=conn.prepareStatement(sql);//获取statement对象
            for(int i=0;i<e.length;i++){
                stat.setObject(i+1,e[i]);
            }
            rest=stat.executeQuery();
            rsmd=rest.getMetaData();
            while(rest.next()){
                Map<String,Object> map=new HashMap<>();
                for(int i=1;i<=rsmd.getColumnCount();i++){
                    map.put(rsmd.getColumnName(i),rest.getObject(i));
                }
                list.add(map);
            }
        } catch (SQLException e1) {
            throw new RuntimeException(e1);
        }finally {
            closeSrc();
        }
        return list;
    }
}
